<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-11-8
 * Time: 上午9:37
 * 自动注册监听者
 */
namespace Event;

abstract class EventAutoRegister{
  /**
   * 暂时先这样处理
   * @var array 静态配置event => listener映射关系
   */
  public static $allListeners = [
    "Event\LoginEvent" => [
      "\Event\generateTokenListener",
      "\Event\CountUserNumberListener",
    ]
  ];

  /**
   * @return Listener 返回自动注册的listener
   */
  abstract protected function listener():Listener;

  /**
   * 注册listener到事件 暂时不需要
   * @throws \Exception
   */
  public function addListener(){
    $listener = $this->listener();
    if (!$listener->event->canAutoRegister()){
      throw new \Exception(get_class($listener->event)." not can auto register");
    }
    $event_name = $listener->event->getId();
    if (!array_key_exists($listener->event->getId(),self::$allListeners)){
      self::$allListeners[$event_name] = [];
    }
    array_push(self::$allListeners[$event_name],$listener->getClassSign());
  }

  /**
   * 自动注册所有的listener 暂时不需要
   */
  static public function autoRegister(){

  }

}